<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.3.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"example.com","root":"/","scheme":"Muse","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.json"};
  </script>

  <meta name="description" content="​         原文链接：https:&#x2F;&#x2F;blog.csdn.net&#x2F;u014421313&#x2F;article&#x2F;details&#x2F;125466427?utm_medium&#x3D;distribute.pc_relevant.none-task-blog-2~default~baidujs_baidulandingword~default-0-125466427-blog-130660447.235^v39">
<meta property="og:type" content="article">
<meta property="og:title" content="ESP32 Arduino通过MQTT上传数据至OneNet">
<meta property="og:url" content="http://example.com/2023/12/09/ESP32%20Arduino%E9%80%9A%E8%BF%87MQTT%E4%B8%8A%E4%BC%A0%E6%95%B0%E6%8D%AE%E8%87%B3OneNet/index.html">
<meta property="og:site_name" content="学无止境">
<meta property="og:description" content="​         原文链接：https:&#x2F;&#x2F;blog.csdn.net&#x2F;u014421313&#x2F;article&#x2F;details&#x2F;125466427?utm_medium&#x3D;distribute.pc_relevant.none-task-blog-2~default~baidujs_baidulandingword~default-0-125466427-blog-130660447.235^v39">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://xdl-blog-picture.oss-cn-shanghai.aliyuncs.com/img/202312091834134.png">
<meta property="og:image" content="https://xdl-blog-picture.oss-cn-shanghai.aliyuncs.com/img/202312091835921.png">
<meta property="og:image" content="https://xdl-blog-picture.oss-cn-shanghai.aliyuncs.com/img/202312091925105.png">
<meta property="og:image" content="https://xdl-blog-picture.oss-cn-shanghai.aliyuncs.com/img/202312092022948.png">
<meta property="og:image" content="https://xdl-blog-picture.oss-cn-shanghai.aliyuncs.com/img/202312092034081.png">
<meta property="og:image" content="https://xdl-blog-picture.oss-cn-shanghai.aliyuncs.com/img/202312092042160.png">
<meta property="og:image" content="https://xdl-blog-picture.oss-cn-shanghai.aliyuncs.com/img/202312092123261.png">
<meta property="og:image" content="https://xdl-blog-picture.oss-cn-shanghai.aliyuncs.com/img/202312092108201.png">
<meta property="og:image" content="https://xdl-blog-picture.oss-cn-shanghai.aliyuncs.com/img/202312092113798.png">
<meta property="og:image" content="https://xdl-blog-picture.oss-cn-shanghai.aliyuncs.com/img/202312092114408.png">
<meta property="article:published_time" content="2023-12-09T10:34:52.000Z">
<meta property="article:modified_time" content="2023-12-09T10:34:52.000Z">
<meta property="article:author" content="xudonglei">
<meta property="article:tag" content="Arduino">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://xdl-blog-picture.oss-cn-shanghai.aliyuncs.com/img/202312091834134.png">

<link rel="canonical" href="http://example.com/2023/12/09/ESP32%20Arduino%E9%80%9A%E8%BF%87MQTT%E4%B8%8A%E4%BC%A0%E6%95%B0%E6%8D%AE%E8%87%B3OneNet/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>ESP32 Arduino通过MQTT上传数据至OneNet | 学无止境</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">学无止境</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">Do not bb, show me the example</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-fw fa-home"></i>首页</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-fw fa-tags"></i>标签</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-fw fa-th"></i>分类</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-fw fa-archive"></i>归档</a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://example.com/2023/12/09/ESP32%20Arduino%E9%80%9A%E8%BF%87MQTT%E4%B8%8A%E4%BC%A0%E6%95%B0%E6%8D%AE%E8%87%B3OneNet/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="xudonglei">
      <meta itemprop="description" content="搬砖 嵌入式">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="学无止境">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          ESP32 Arduino通过MQTT上传数据至OneNet
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2023-12-09 18:34:52" itemprop="dateCreated datePublished" datetime="2023-12-09T18:34:52+08:00">2023-12-09</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/%E5%B5%8C%E5%85%A5%E5%BC%8F/" itemprop="url" rel="index"><span itemprop="name">嵌入式</span></a>
                </span>
            </span>

          
            <span id="/2023/12/09/ESP32%20Arduino%E9%80%9A%E8%BF%87MQTT%E4%B8%8A%E4%BC%A0%E6%95%B0%E6%8D%AE%E8%87%B3OneNet/" class="post-meta-item leancloud_visitors" data-flag-title="ESP32 Arduino通过MQTT上传数据至OneNet" title="阅读次数">
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              <span class="post-meta-item-text">阅读次数：</span>
              <span class="leancloud-visitors-count"></span>
            </span>
  
  <span class="post-meta-item">
    
      <span class="post-meta-item-icon">
        <i class="fa fa-comment-o"></i>
      </span>
      <span class="post-meta-item-text">Valine：</span>
    
    <a title="valine" href="/2023/12/09/ESP32%20Arduino%E9%80%9A%E8%BF%87MQTT%E4%B8%8A%E4%BC%A0%E6%95%B0%E6%8D%AE%E8%87%B3OneNet/#valine-comments" itemprop="discussionUrl">
      <span class="post-comments-count valine-comment-count" data-xid="/2023/12/09/ESP32%20Arduino%E9%80%9A%E8%BF%87MQTT%E4%B8%8A%E4%BC%A0%E6%95%B0%E6%8D%AE%E8%87%B3OneNet/" itemprop="commentCount"></span>
    </a>
  </span>
  
  

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <p>​         原文链接：<a target="_blank" rel="noopener" href="https://blog.csdn.net/u014421313/article/details/125466427?utm_medium=distribute.pc_relevant.none-task-blog-2~default~baidujs_baidulandingword~default-0-125466427-blog-130660447.235%5Ev39%5Epc_relevant_anti_vip&amp;spm=1001.2101.3001.4242.1&amp;utm_relevant_index=3">https://blog.csdn.net/u014421313/article/details/125466427?utm_medium=distribute.pc_relevant.none-task-blog-2~default~baidujs_baidulandingword~default-0-125466427-blog-130660447.235^v39^pc_relevant_anti_vip&amp;spm=1001.2101.3001.4242.1&amp;utm_relevant_index=3</a></p>
<h3 id="OneNet平台配置"><a href="#OneNet平台配置" class="headerlink" title="OneNet平台配置"></a><strong>OneNet平台配置</strong></h3><img src="https://xdl-blog-picture.oss-cn-shanghai.aliyuncs.com/img/202312091834134.png" style="zoom:50%;">

<img src="https://xdl-blog-picture.oss-cn-shanghai.aliyuncs.com/img/202312091835921.png" style="zoom:67%;">

<p><img src="https://xdl-blog-picture.oss-cn-shanghai.aliyuncs.com/img/202312091925105.png"></p>
<img src="https://xdl-blog-picture.oss-cn-shanghai.aliyuncs.com/img/202312092022948.png" style="zoom:67%;">

<p>​        添加好产品之后，就可以添加设备了。因为产品下面可以包含多个设备，并且这样的设备就是对应的硬件，所以一定要添加设备方可使用：</p>
<img src="https://xdl-blog-picture.oss-cn-shanghai.aliyuncs.com/img/202312092034081.png" style="zoom:67%;">

<p>​        添加设备里面的有个鉴权信息，这个非常重要，后面在设备登录的时候，需要用到，显示应该是可以自己定义的数据，具体鉴权信息用户可以自己添加，使用数字与符号，尽量不要用一些特殊字符代替。</p>
<p>​        这样就注册好了，然后设备会显示离线，这时只要模块发送数据到 ONENET 平台进行激活就可以了。</p>
<h3 id="ESP32安装库"><a href="#ESP32安装库" class="headerlink" title="ESP32安装库"></a><strong>ESP32安装库</strong></h3><p>​        打开arduino选择“工具”里的管理库，在管理库里搜索：Pub SubClient,安装完成后即可使用该库。</p>
<img src="https://xdl-blog-picture.oss-cn-shanghai.aliyuncs.com/img/202312092042160.png" style="zoom:67%;">

<h3 id="代码示例"><a href="#代码示例" class="headerlink" title="代码示例"></a>代码示例</h3><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;Arduino.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&quot;WiFi.h&quot;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&quot;PubSubClient.h&quot;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&quot;Ticker.h&quot;</span></span></span><br><span class="line"> </span><br><span class="line"><span class="keyword">const</span> <span class="keyword">char</span> *ssid = <span class="string">&quot;360WiFi-99B5DF&quot;</span>;         <span class="comment">//wifi名</span></span><br><span class="line"><span class="keyword">const</span> <span class="keyword">char</span> *password = <span class="string">&quot;xxxxxxxxx&quot;</span>;          <span class="comment">//wifi密码</span></span><br><span class="line"><span class="keyword">const</span> <span class="keyword">char</span> *mqtt_server = <span class="string">&quot;183.230.40.39&quot;</span>;   <span class="comment">//onenet 的 IP地址</span></span><br><span class="line"> </span><br><span class="line"><span class="meta">#<span class="meta-keyword">define</span> mqtt_devid <span class="meta-string">&quot;1172115522&quot;</span>    <span class="comment">//设备ID</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">define</span> mqtt_pubid <span class="meta-string">&quot;622583&quot;</span>        <span class="comment">//产品ID</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">define</span> mqtt_password <span class="meta-string">&quot;xxxxxxxxxx&quot;</span>  <span class="comment">//鉴权信息</span></span></span><br><span class="line"> </span><br><span class="line">WiFiClient espClient;           <span class="comment">//创建一个WIFI连接客户端</span></span><br><span class="line"><span class="function">PubSubClient <span class="title">client</span><span class="params">(espClient)</span></span>; <span class="comment">// 创建一个PubSub客户端, 传入创建的WIFI客户端</span></span><br><span class="line"> </span><br><span class="line"><span class="keyword">char</span> msg_buf[<span class="number">200</span>];                                    <span class="comment">//发送信息缓冲区</span></span><br><span class="line"><span class="keyword">char</span> dataTemplate[] = <span class="string">&quot;&#123;\&quot;temp\&quot;:%.2f,\&quot;hum\&quot;:%.2f&#125;&quot;</span>; <span class="comment">//信息模板</span></span><br><span class="line"><span class="keyword">char</span> msgJson[<span class="number">75</span>];                                     <span class="comment">//要发送的json格式的数据</span></span><br><span class="line"><span class="keyword">unsigned</span> <span class="keyword">short</span> json_len = <span class="number">0</span>;                          <span class="comment">//json长度</span></span><br><span class="line">Ticker tim1;                                          <span class="comment">//定时器,用来循环上传数据</span></span><br><span class="line"> </span><br><span class="line"><span class="comment">//连接WIFI相关函数</span></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">setupWifi</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">  delay(<span class="number">10</span>);</span><br><span class="line">  Serial.println(<span class="string">&quot;连接WIFI&quot;</span>);</span><br><span class="line">  WiFi.begin(ssid, password);</span><br><span class="line">  <span class="keyword">while</span> (!WiFi.isConnected())</span><br><span class="line">  &#123;</span><br><span class="line">    Serial.print(<span class="string">&quot;.&quot;</span>);</span><br><span class="line">    delay(<span class="number">500</span>);</span><br><span class="line">  &#125;</span><br><span class="line">  Serial.println(<span class="string">&quot;OK&quot;</span>);</span><br><span class="line">  Serial.println(<span class="string">&quot;Wifi连接成功&quot;</span>);</span><br><span class="line">&#125;</span><br><span class="line"> </span><br><span class="line"><span class="comment">//收到主题下发的回调, 注意这个回调要实现三个形参 1:topic 主题, 2: payload: 传递过来的信息 3: length: 长度</span></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">callback</span><span class="params">(<span class="keyword">char</span> *topic, byte *payload, <span class="keyword">unsigned</span> <span class="keyword">int</span> length)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">  Serial.println(<span class="string">&quot;message rev:&quot;</span>);</span><br><span class="line">  Serial.println(topic);</span><br><span class="line">  <span class="keyword">for</span> (<span class="keyword">size_t</span> i = <span class="number">0</span>; i &lt; length; i++)</span><br><span class="line">  &#123;</span><br><span class="line">    Serial.print((<span class="keyword">char</span>)payload[i]);</span><br><span class="line">  &#125;</span><br><span class="line">  Serial.println();</span><br><span class="line">&#125;</span><br><span class="line"> </span><br><span class="line"><span class="comment">//向主题发送模拟的温湿度数据</span></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">sendTempAndHumi</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">  <span class="keyword">if</span> (client.connected())</span><br><span class="line">  &#123;</span><br><span class="line">    <span class="built_in">snprintf</span>(msgJson, <span class="number">40</span>, dataTemplate, <span class="number">22.31</span>, <span class="number">25.92</span>); <span class="comment">//将模拟温湿度数据套入dataTemplate模板中, 生成的字符串传给msgJson</span></span><br><span class="line">    json_len = <span class="built_in">strlen</span>(msgJson);                        <span class="comment">//msgJson的长度</span></span><br><span class="line">    msg_buf[<span class="number">0</span>] = <span class="keyword">char</span>(<span class="number">0x03</span>);                           <span class="comment">//要发送的数据必须按照ONENET的要求发送, 根据要求,数据第一位是3</span></span><br><span class="line">    msg_buf[<span class="number">1</span>] = <span class="keyword">char</span>(json_len &gt;&gt; <span class="number">8</span>);                  <span class="comment">//数据第二位是要发送的数据长度的高八位</span></span><br><span class="line">    msg_buf[<span class="number">2</span>] = <span class="keyword">char</span>(json_len &amp; <span class="number">0xff</span>);                <span class="comment">//数据第三位是要发送数据的长度的低八位</span></span><br><span class="line">    <span class="built_in">memcpy</span>(msg_buf + <span class="number">3</span>, msgJson, <span class="built_in">strlen</span>(msgJson));    <span class="comment">//从msg_buf的第四位开始,放入要传的数据msgJson</span></span><br><span class="line">    msg_buf[<span class="number">3</span> + <span class="built_in">strlen</span>(msgJson)] = <span class="number">0</span>;                 <span class="comment">//添加一个0作为最后一位, 这样要发送的msg_buf准备好了</span></span><br><span class="line">    Serial.print(<span class="string">&quot;public message:&quot;</span>);</span><br><span class="line">    Serial.println(msgJson);</span><br><span class="line">    client.publish(<span class="string">&quot;$dp&quot;</span>, (<span class="keyword">uint8_t</span> *)msg_buf, <span class="number">3</span> + <span class="built_in">strlen</span>(msgJson)); <span class="comment">//发送数据到主题$dp</span></span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"> </span><br><span class="line"><span class="comment">//重连函数, 如果客户端断线,可以通过此函数重连</span></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">clientReconnect</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">  <span class="keyword">while</span> (!client.connected()) <span class="comment">//再重连客户端</span></span><br><span class="line">  &#123;</span><br><span class="line">    Serial.println(<span class="string">&quot;reconnect MQTT...&quot;</span>);</span><br><span class="line">    <span class="keyword">if</span> (client.connect(mqtt_devid, mqtt_pubid, mqtt_password))</span><br><span class="line">    &#123;</span><br><span class="line">      Serial.println(<span class="string">&quot;connected&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">else</span></span><br><span class="line">    &#123;</span><br><span class="line">      Serial.println(<span class="string">&quot;failed&quot;</span>);</span><br><span class="line">      Serial.println(client.state());</span><br><span class="line">      Serial.println(<span class="string">&quot;try again in 5 sec&quot;</span>);</span><br><span class="line">      delay(<span class="number">5000</span>);</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"> </span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">setup</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">  Serial.begin(<span class="number">115200</span>);                                  <span class="comment">//初始化串口</span></span><br><span class="line">  delay(<span class="number">3000</span>);                                           <span class="comment">//这个延时是为了让我打开串口助手</span></span><br><span class="line">  setupWifi();                                           <span class="comment">//调用函数连接WIFI</span></span><br><span class="line">  client.setServer(mqtt_server, <span class="number">6002</span>);                   <span class="comment">//设置客户端连接的服务器,连接Onenet服务器, 使用6002端口</span></span><br><span class="line">  client.connect(mqtt_devid, mqtt_pubid, mqtt_password); <span class="comment">//客户端连接到指定的产品的指定设备.同时输入鉴权信息</span></span><br><span class="line">  client.setCallback(callback);                          <span class="comment">//设置好客户端收到信息是的回调</span></span><br><span class="line">  tim1.attach(<span class="number">20</span>, sendTempAndHumi);                      <span class="comment">//定时每20秒调用一次发送数据函数sendTempAndHumi</span></span><br><span class="line">&#125;</span><br><span class="line"> </span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">loop</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">  <span class="keyword">if</span> (!WiFi.isConnected()) <span class="comment">//先看WIFI是否还在连接</span></span><br><span class="line">  &#123;</span><br><span class="line">    setupWifi();</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">if</span> (!client.connected()) <span class="comment">//如果客户端没连接ONENET, 重新连接</span></span><br><span class="line">  &#123;</span><br><span class="line">    clientReconnect();</span><br><span class="line">  &#125;</span><br><span class="line">  client.loop(); <span class="comment">//客户端循环检测</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>​        ESP32连接到WiFi网络：确定连接WiFi的SSID和password，只需更改示例代码的ssid和password。”WiFiClient”是一个用于建立 TCP 连接的类，而 PubSubClient是一个 MQTT 客户端库，用于发布和接收 MQTT 消息。在这里，WiFiClient 用于建立与 MQTT 服务器的连接，而 PubSubClient用于发布和接收 MQTT 消息。</p>
<img src="https://xdl-blog-picture.oss-cn-shanghai.aliyuncs.com/img/202312092123261.png" style="zoom:67%;">

<p><img src="https://xdl-blog-picture.oss-cn-shanghai.aliyuncs.com/img/202312092108201.png"></p>
<p>​        可以上传数据,也能接收到OneNet下发的命令:</p>
<img src="https://xdl-blog-picture.oss-cn-shanghai.aliyuncs.com/img/202312092113798.png" style="zoom:67%;">

<p><img src="https://xdl-blog-picture.oss-cn-shanghai.aliyuncs.com/img/202312092114408.png"></p>

    </div>

    
    
    

      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/Arduino/" rel="tag"># Arduino</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2023/12/07/%E7%94%B5%E5%8E%8B%E8%B7%9F%E9%9A%8F%E5%99%A8%E4%BD%9C%E7%94%A8/" rel="prev" title="电压跟随器作用">
      <i class="fa fa-chevron-left"></i> 电压跟随器作用
    </a></div>
      <div class="post-nav-item">
    <a href="/2023/12/10/%E4%BD%8E%E9%80%9A%E6%BB%A4%E6%B3%A2multisim%E4%BB%BF%E7%9C%9F/" rel="next" title="低通滤波multisim仿真">
      低通滤波multisim仿真 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          
    <div class="comments" id="valine-comments"></div>

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#OneNet%E5%B9%B3%E5%8F%B0%E9%85%8D%E7%BD%AE"><span class="nav-number">1.</span> <span class="nav-text">OneNet平台配置</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#ESP32%E5%AE%89%E8%A3%85%E5%BA%93"><span class="nav-number">2.</span> <span class="nav-text">ESP32安装库</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E4%BB%A3%E7%A0%81%E7%A4%BA%E4%BE%8B"><span class="nav-number">3.</span> <span class="nav-text">代码示例</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">xudonglei</p>
  <div class="site-description" itemprop="description">搬砖 嵌入式</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">283</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">19</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">67</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2024</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">xudonglei</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://muse.theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Muse</a> 强力驱动
  </div>

        








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/muse.js"></script>


<script src="/js/next-boot.js"></script>




  




  
<script src="/js/local-search.js"></script>













  

  


<script>
NexT.utils.loadComments(document.querySelector('#valine-comments'), () => {
  NexT.utils.getScript('//unpkg.com/valine/dist/Valine.min.js', () => {
    var GUEST = ['nick', 'mail', 'link'];
    var guest = 'nick,mail,link';
    guest = guest.split(',').filter(item => {
      return GUEST.includes(item);
    });
    new Valine({
      el         : '#valine-comments',
      verify     : false,
      notify     : false,
      appId      : 'BT0Qw9HcTpPv1a6cT1iDBXKz-gzGzoHsz',
      appKey     : 'LMCMh8v02JTMFAwKNRcgoizI',
      placeholder: "Just go go",
      avatar     : 'mm',
      meta       : guest,
      pageSize   : '10' || 10,
      visitor    : true,
      lang       : 'zh-CN' || 'zh-cn',
      path       : location.pathname,
      recordIP   : false,
      serverURLs : ''
    });
  }, window.Valine);
});
</script>

</body>
</html>
